<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑 GitHub 监测任务' : '新建 GitHub 监测任务'"
    width="600px"
    :close-on-click-modal="false"
    :before-close="handleBeforeClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      size="default"
    >
      <!-- 任务名称 -->
      <el-form-item label="任务名称" prop="task_name" required>
        <el-input
          v-model="formData.task_name"
          placeholder="请输入任务名称"
          clearable
        />
      </el-form-item>

      <!-- 主关键词 -->
      <el-form-item label="主关键词" prop="main_keyword" required>
        <el-input
          v-model="formData.main_keyword"
          placeholder="请输入主关键词（如公司名称）"
          clearable
        />
      </el-form-item>

      <!-- 场景类型 -->
      <el-form-item label="场景类型" prop="scenario_types">
        <el-checkbox-group v-model="formData.scenario_types">
          <el-checkbox label="password">password</el-checkbox>
          <el-checkbox label="apikey">apikey</el-checkbox>
          <el-checkbox label="database">database</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <!-- 启用调度 -->
      <el-form-item label="启用调度" prop="schedule_enabled">
        <el-switch v-model="formData.schedule_enabled" />
      </el-form-item>

      <!-- 执行频率 -->
      <el-form-item
        v-if="formData.schedule_enabled"
        label="执行频率"
        prop="cron_expression"
      >
        <el-radio-group v-model="frequencyType" @change="handleFrequencyChange">
          <el-radio label="every6hours">每6小时</el-radio>
          <el-radio label="daily">每天</el-radio>
          <el-radio label="custom">自定义</el-radio>
        </el-radio-group>
        <el-input
          v-if="frequencyType === 'custom'"
          v-model="formData.cron_expression"
          placeholder="请输入 Cron 表达式，如：0 */6 * * *"
          style="margin-top: 10px"
          clearable
        />
      </el-form-item>

      <!-- 描述 -->
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入任务描述（可选）"
          clearable
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { createGithubTask, updateGithubTask } from "../../../servers";

interface Props {
  modelValue: boolean;
  taskData?: any; // 编辑时的任务数据
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  taskData: null,
});

// 判断是否为编辑模式
const isEdit = computed(() => !!props.taskData);

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "success"): void;
  (e: "cancel"): void;
}>();

const formRef = ref<FormInstance | null>(null);
const loading = ref(false);
const frequencyType = ref<"every6hours" | "daily" | "custom">("every6hours");

// 表单数据
const formData = reactive({
  task_name: "",
  main_keyword: "",
  scenario_types: [] as string[],
  schedule_enabled: false,
  cron_expression: "",
  description: "",
});

// 表单验证规则
const formRules: FormRules = {
  task_name: [
    { required: true, message: "请输入任务名称", trigger: "blur" },
    {
      min: 1,
      max: 100,
      message: "任务名称长度在 1 到 100 个字符",
      trigger: "blur",
    },
  ],
  main_keyword: [
    { required: true, message: "请输入主关键词", trigger: "blur" },
    {
      min: 1,
      max: 50,
      message: "主关键词长度在 1 到 50 个字符",
      trigger: "blur",
    },
  ],
  cron_expression: [
    {
      validator: (rule, value, callback) => {
        if (formData.schedule_enabled && frequencyType.value === "custom") {
          if (!value || value.trim() === "") {
            callback(new Error("请输入 Cron 表达式"));
          } else {
            // 简单的 Cron 表达式验证：5个字段，用空格分隔
            const parts = value.trim().split(/\s+/);
            if (parts.length !== 5) {
              callback(
                new Error("Cron 表达式必须包含5个字段（分 时 日 月 周）")
              );
            } else {
              callback();
            }
          }
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 计算 visible
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => {
    emit("update:modelValue", value);
  },
});

// 监听弹窗打开，重置或填充表单
watch(visible, (newVal) => {
  if (newVal) {
    if (isEdit.value && props.taskData) {
      fillFormFromTaskData();
    } else {
      resetForm();
    }
  }
});

// 从任务数据填充表单
const fillFormFromTaskData = () => {
  const task = props.taskData;
  formData.task_name = task.task_name || "";
  formData.main_keyword = task.main_keyword || "";

  // 解析场景类型
  try {
    if (task.scenario_types) {
      const scenarios = JSON.parse(task.scenario_types);
      formData.scenario_types = Array.isArray(scenarios) ? scenarios : [];
    } else {
      formData.scenario_types = [];
    }
  } catch (e) {
    formData.scenario_types = [];
  }

  formData.schedule_enabled = task.schedule_enabled || false;
  formData.cron_expression = task.cron_expression || "";
  formData.description = task.description || "";

  // 根据 cron 表达式设置频率类型
  if (formData.cron_expression) {
    if (formData.cron_expression === "0 */6 * * *") {
      frequencyType.value = "every6hours";
    } else if (formData.cron_expression === "0 0 * * *") {
      frequencyType.value = "daily";
    } else {
      frequencyType.value = "custom";
    }
  } else {
    frequencyType.value = "every6hours";
  }

  formRef.value?.clearValidate();
};

// 处理执行频率变化
const handleFrequencyChange = (value: string) => {
  if (value === "every6hours") {
    formData.cron_expression = "0 */6 * * *";
  } else if (value === "daily") {
    formData.cron_expression = "0 0 * * *";
  } else {
    formData.cron_expression = "";
  }
};

// 初始化时设置默认的 cron 表达式
watch(
  () => formData.schedule_enabled,
  (enabled) => {
    if (enabled && !formData.cron_expression) {
      handleFrequencyChange(frequencyType.value);
    }
  }
);

// 重置表单
const resetForm = () => {
  formData.task_name = "";
  formData.main_keyword = "";
  formData.scenario_types = [];
  formData.schedule_enabled = false;
  formData.cron_expression = "";
  formData.description = "";
  frequencyType.value = "every6hours";
  formRef.value?.clearValidate();
};

// 关闭前回调
const handleBeforeClose = () => {
  visible.value = false;
};

// 取消
const handleCancel = () => {
  visible.value = false;
  emit("cancel");
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    // 表单验证
    await formRef.value.validate();

    // 准备提交数据
    const submitData: any = {
      task_name: formData.task_name.trim(),
      main_keyword: formData.main_keyword.trim(),
    };

    // 场景类型（如果有选择）
    if (formData.scenario_types.length > 0) {
      submitData.scenario_types = JSON.stringify(formData.scenario_types);
    }

    // 如果启用了调度，添加调度相关字段
    if (formData.schedule_enabled) {
      submitData.schedule_enabled = true;
      if (formData.cron_expression) {
        submitData.cron_expression = formData.cron_expression.trim();
      }
    } else {
      submitData.schedule_enabled = false;
    }

    // 描述（可选）
    if (formData.description?.trim()) {
      submitData.description = formData.description.trim();
    }

    loading.value = true;

    let result;
    if (isEdit.value && props.taskData?.id) {
      // 编辑模式
      result = await updateGithubTask(props.taskData.id, submitData);
      if (result.code === 2000) {
        ElMessage.success("任务更新成功");
        visible.value = false;
        emit("success");
      } else {
        ElMessage.error(result.message || "更新任务失败");
      }
    } else {
      // 新增模式
      result = await createGithubTask(submitData);
      if (result.code === 2000) {
        ElMessage.success("任务创建成功");
        visible.value = false;
        emit("success");
        resetForm();
      } else {
        ElMessage.error(result.message || "创建任务失败");
      }
    }
  } catch (error: any) {
    if (error !== false) {
      // 验证失败时 error 为 false，不需要处理
      ElMessage.error(error?.message || "创建任务失败");
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped lang="scss">
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

:deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
</style>
